package cn.fl.finance.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.dto.SysOrgDTO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.dk.web.transform.KeyValueVOTransform;
import cn.fl.finance.condition.FinLoanInfoQC;
import cn.fl.finance.constant.FinLoanConstant;
import cn.fl.finance.dto.FinLoanInfoDTO;
import cn.fl.finance.service.IFinLoanInfoService;
import cn.fl.finance.vo.FinLoanInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 借款记录表 控制层
 */
@Controller
@RequestMapping("/finance/finLoanInfo")
public class FinLoanInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(FinLoanInfoController.class);

	/**
	 * FinLoanInfo 服务层BEAN
	 */
	@Autowired
	private IFinLoanInfoService finLoanInfoService;

	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	@Autowired
	private ICstBscInfoService cstBscInfoService;
	@Autowired
	private ISysOrgApiService sysOrgApiService;

	@Autowired
	private IPrjBscInfoService prjBscInfoService;//项目基础信息表

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView view = new ModelAndView("finance/loaninfo/finLoanInfoList");
        // 借款状态
        List<SysDictionaryDTO> loanStsCd = sysDictionaryApiService.searchGroup(FinLoanConstant.SYS_CD, FinLoanConstant.ORG_CD, FinLoanConstant.FIN_LOAN_STS_DIC);
        view.addObject("loanStsCdList", KeyValueVOTransform.toVoList(loanStsCd));
        // 事业部
        List<KeyValueVO> orgList = this.cstBscInfoService.searchBusinessOrgList();
        view.addObject("buOrgCdList", JSON.toJSONString(orgList));
        return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("finance/finLoanInfo/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String cstMgrNm = request.getParameter("cstMgrNm");
		String cstMgrCd = request.getParameter("cstMgrCd");
		String startLoanTm = request.getParameter("startLoanTm");
		String endLoanTm = request.getParameter("endLoanTm");
		String minLoanAmt = request.getParameter("minLoanAmt");
		String maxLoanAmt = request.getParameter("maxLoanAmt");
		String buOrgCd = request.getParameter("buOrgCd");
		String loanStsCd = request.getParameter("loanStsCd");
		String flowNo = request.getParameter("flowNo"); //流程编号查询条件
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		FinLoanInfoQC qc = new FinLoanInfoQC();
		if (StringUtils.isNotEmpty(cstMgrNm)) {
			qc.setCstMgrNm(cstMgrNm);
		}
		if (StringUtils.isNotEmpty(flowNo)) {
			qc.setpNo(flowNo);
		}
		if (StringUtils.isNotEmpty(cstMgrCd)) {
			qc.setCstMgrCd(cstMgrCd);
		}
		if (StringUtils.isNotEmpty(startLoanTm)) {
			qc.setStartLoanTm(startLoanTm);
		}
		if (StringUtils.isNotEmpty(endLoanTm)) {
			qc.setEndLoanTm(endLoanTm);
		}
		if (StringUtils.isNotEmpty(minLoanAmt)) {
			Long minLoanAmtLong = DecimalUtils.convertYuanToFen(Double.parseDouble(minLoanAmt));
			qc.setMinLoanAmt(minLoanAmtLong);
		}
		if (StringUtils.isNotEmpty(maxLoanAmt)) {
			Long maxLoanAmtLong = DecimalUtils.convertYuanToFen(Double.parseDouble(maxLoanAmt));
			qc.setMaxLoanAmt(maxLoanAmtLong);
		}
		if (StringUtils.isNotEmpty(buOrgCd)) {
			qc.setBuOrgCd(buOrgCd);
		}
		if (StringUtils.isNotEmpty(loanStsCd)) {
			qc.setLoanStsCd(loanStsCd);
		}
		qc.setUsrId(CurrentThreadContext.getCurrentUserId());
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		qc.setCstMgrOrgCd(CurrentThreadContext.getCurrentOrgCd());
		page.setCondition(qc);
		//TODO SOMETHING
		try{
			Pager pager = this.finLoanInfoService.searchListPage(page);
			List<FinLoanInfoVO> list = (List<FinLoanInfoVO>) pager.getResultList();
			//设置数据字典
			prepare(request,list);
			ListPageVO<FinLoanInfoVO> listPage = new ListPageVO<FinLoanInfoVO>(list, pager.getTotalCount());
			BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
			return listPage;
		}catch (Exception ex) {
			BaseLogUtils.error(logger, "initList", "借款记录查询数据失败：" + ex.getMessage(), CurrentThreadContext.getCurrentUserName(),ex);
		}
		return null;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.finLoanInfoService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			FinLoanInfoVO vo = this.finLoanInfoService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		FinLoanInfoVO entity = null;
		try {
			entity = new FinLoanInfoVO();
			//TODO ADD PARAM
			Long id = this.finLoanInfoService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	//加载数据字典数据
	private void prepare(HttpServletRequest request,List<FinLoanInfoVO> loanInfoList) {
		//事业部
		List<SysOrgDTO> orgList = this.sysOrgApiService.searchListByOrgTypCd(CurrentThreadContext.getCurrentSysCd());
		Map<String, String> orgMap = null;
		if (CollectionUtils.isNotEmpty(orgList)) {
			orgMap = new HashMap<>(orgList.size());
			for (SysOrgDTO orgDTO : orgList) {
				orgMap.put(orgDTO.getOrgCd(), orgDTO.getOrgNm());
			}
		}

		//借款状态
		//List<KeyValueVO> loanStsCds = this.sysDictionaryApiService.getKvList(FinLoanConstant.FIN_LOAN_STS_DIC, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		Map<String, String> loanStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), FinLoanConstant.FIN_LOAN_STS_DIC);
		if(CollectionUtils.isNotEmpty(loanInfoList)){
			for(FinLoanInfoVO f : loanInfoList){

				if (CollectionUtils.isMapNotEmpty(orgMap) && orgMap.containsKey(f.getBuOrgCd())) {
					f.setBuOrgCd(orgMap.get(f.getBuOrgCd()));
				}

				if(CollectionUtils.isMapNotEmpty(loanStsCdMap) && loanStsCdMap.containsKey(f.getLoanStsCd())){
					f.setLoanStsCd(loanStsCdMap.get(f.getLoanStsCd()));
				}
			}
		}
	}

	/**
	 * 到借款还款管理列表
	 */
	@RequestMapping(value = "/toLoanPayPage.do", method = { RequestMethod.GET})
	public ModelAndView toLoanPayPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		ModelAndView view = new ModelAndView("finance/loaninfo/finLoanPayList");
		// 事业部
		List<KeyValueVO> orgList = this.cstBscInfoService.searchBusinessOrgList();
		view.addObject("buOrgCdList", JSON.toJSONString(orgList));

		//所属公司 start
		String currentOrgCd = CurrentThreadContext.getCurrentOrgCd();
		if(currentOrgCd.length()>8){
			if(CollectionUtils.isNotEmpty(orgList)){
				for(KeyValueVO kv:orgList){
					if(kv.getKey().equals(currentOrgCd.substring(0, 8))){
						view.addObject("currOrg", CurrentThreadContext.getCurrentOrgCd());
						break;
					}
				}
			}
		}
		//所属公司 end

		// 借款类型
		List<SysDictionaryDTO> loanTypCdList = sysDictionaryApiService.searchGroup(FinLoanConstant.SYS_CD, FinLoanConstant.ORG_CD, FinLoanConstant.FIN_LOAN_TYP_DIDC);
		view.addObject("loanTypCdList", loanTypCdList);
		// 所属区域
		List<SysDictionaryDTO> regionList = sysDictionaryApiService.searchGroup(FinLoanConstant.SYS_CD, FinLoanConstant.ORG_CD, FinLoanConstant.CODE_REGION_CD);
		view.addObject("regionList", regionList);

		return view;
	}

	/**
	 * 借款还款管理列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initLoanPayList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initLoanPayList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String cstMgrNm = request.getParameter("cstMgrNm");
		String cstMgrCd = request.getParameter("cstMgrCd");
		String contNo = request.getParameter("contNo");
		String paySchNo = request.getParameter("paySchNo");
		String minLoanAmt = request.getParameter("minLoanAmt");
		String maxLoanAmt = request.getParameter("maxLoanAmt");
		String capCstMgrNm = request.getParameter("capCstMgrNm");
		String buOrgCd = request.getParameter("buOrgCd");
		String startLoanTm = request.getParameter("startLoanTm");
		String endLoanTm = request.getParameter("endLoanTm");
		String loanTypCd = request.getParameter("loanTypCd");
		String pNo = request.getParameter("pNo");
		String cstMgrRgnCd = request.getParameter("cstMgrRgnCd");

		//String cstMgrOrgCd = request.getParameter("cstMgrOrgCd");//所属公司
		String cstMgrOrgCdCap = request.getParameter("cstMgrOrgCdCap");//所属公司

		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		FinLoanInfoQC qc = new FinLoanInfoQC();
		if (StringUtils.isNotEmpty(cstMgrRgnCd)) {
			qc.setCstMgrRgnCd(cstMgrRgnCd);
		}
		if (StringUtils.isNotEmpty(cstMgrNm)) {
			qc.setCstMgrNm(cstMgrNm);
		}
		if (StringUtils.isNotEmpty(cstMgrCd)) {
			qc.setCstMgrCd(cstMgrCd);
		}
		if (StringUtils.isNotEmpty(contNo)) {
			qc.setContNo(contNo);
		}
		if (StringUtils.isNotEmpty(paySchNo)) {
			qc.setPaySchNo(paySchNo);
		}
		if (StringUtils.isNotEmpty(minLoanAmt)) {
			Long minLoanAmtLong = DecimalUtils.convertYuanToFen(Double.parseDouble(minLoanAmt));
			qc.setMinLoanAmt(minLoanAmtLong);
		}
		if (StringUtils.isNotEmpty(maxLoanAmt)) {
			Long maxLoanAmtLong = DecimalUtils.convertYuanToFen(Double.parseDouble(maxLoanAmt));
			qc.setMaxLoanAmt(maxLoanAmtLong);
		}
		if (StringUtils.isNotEmpty(capCstMgrNm)) {
			qc.setCapCstMgrNm(capCstMgrNm);
		}
		if (StringUtils.isNotEmpty(buOrgCd)) {
			qc.setBuOrgCd(buOrgCd);
		}

		if (StringUtils.isNotEmpty(startLoanTm)) {
			qc.setStartLoanTm(startLoanTm);
		}
		if (StringUtils.isNotEmpty(endLoanTm)) {
			qc.setEndLoanTm(endLoanTm);
		}

		if (StringUtils.isNotEmpty(loanTypCd)) {
			qc.setLoanTypCd(loanTypCd);
		}

		if (StringUtils.isNotEmpty(pNo)) {
			qc.setpNo(pNo);
		}

		if (StringUtils.isNotBlank(cstMgrOrgCdCap)) {
			//qc.setCstMgrOrgCd(cstMgrOrgCd);
			qc.setCstMgrOrgCdCap(cstMgrOrgCdCap);
		}
		qc.setUsrId(CurrentThreadContext.getCurrentUserId());
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
        qc.setCstMgrOrgCd(CurrentThreadContext.getCurrentOrgCd());
		page.setCondition(qc);
		//TODO SOMETHING
		try{
			Pager pager = this.finLoanInfoService.selectLoanPayPage(page);
			List<FinLoanInfoDTO> list = (List<FinLoanInfoDTO>) pager.getResultList();
			if (CollectionUtils.isEmpty(list)) {
			    list = new ArrayList<FinLoanInfoDTO>();
            }
			//设置数据字典
			prepare2(request,list);
			ListPageVO<FinLoanInfoDTO> listPage = new ListPageVO<FinLoanInfoDTO>(list, pager.getTotalCount());
			BaseLogUtils.info(logger, "initLoanPayList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
			return listPage;
		}catch (Exception ex) {
			BaseLogUtils.error(logger, "initLoanPayList", "借款还款管理列表查询数据失败：" + ex.toString(), CurrentThreadContext.getCurrentUserName(),ex);
		}
		return null;
	}

	//加载数据字典数据
	private void prepare2(HttpServletRequest request,List<FinLoanInfoDTO> loanInfoList) {
		//事业部
		List<SysOrgDTO> orgList = this.sysOrgApiService.searchListByOrgTypCd(CurrentThreadContext.getCurrentSysCd());
		Map<String, String> orgMap = null;
		if (CollectionUtils.isNotEmpty(orgList)) {
			orgMap = new HashMap<>(orgList.size());
			for (SysOrgDTO orgDTO : orgList) {
				orgMap.put(orgDTO.getOrgCd(), orgDTO.getOrgNm());
			}
		}

		//借款类型
		Map<String, String> loanTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), FinLoanConstant.FIN_LOAN_TYP_DIDC);
		Map<String, String> cstMgrRgnCdMapMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), FinLoanConstant.CODE_REGION_CD);
		if(CollectionUtils.isNotEmpty(loanInfoList)){
			for(FinLoanInfoDTO f : loanInfoList){

				if (CollectionUtils.isMapNotEmpty(orgMap) && orgMap.containsKey(f.getBuOrgCd())) {
					f.setBuOrgCd(orgMap.get(f.getBuOrgCd()));
				}

				if(CollectionUtils.isMapNotEmpty(loanTypCdMap) && loanTypCdMap.containsKey(f.getLoanTypCd())){
					f.setLoanTypCd(loanTypCdMap.get(f.getLoanTypCd()));
				}

				if(CollectionUtils.isMapNotEmpty(cstMgrRgnCdMapMap) && cstMgrRgnCdMapMap.containsKey(f.getCstMgrRgnCd())){
					f.setCstMgrRgnCd(cstMgrRgnCdMapMap.get(f.getCstMgrRgnCd()));
				}
			}
		}
	}
}

